package ai4games_tests.soccer;

import game2dai.World;
import game2dai.entities.BaseEntity;
import game2dai.fsm.State;
import game2dai.fsm.Telegram;
import game2dai.maths.MathUtils;
import game2dai.steering.SBF;

public class PlayerReturnToRegion extends State implements Constants {


	private static PlayerReturnToRegion instance = null;

	public static PlayerReturnToRegion state(){
		if(instance == null){
			instance = new PlayerReturnToRegion();
			instance.name = "To Region";
		}
		return instance;
	}

	@Override
	public void enter(BaseEntity owner) {
		PlayerBase player = (PlayerBase) owner;
		player.targetPos.set(player.team.pitch.getRegion(player.regionToUse).centre);
		player.targetPos.add(MathUtils.randomClamped(), MathUtils.randomClamped());
		player.AP().arriveOn(player.targetPos, SBF.FAST);
	}

	@Override
	public void execute(BaseEntity owner, double deltaTime, World world) {
		PlayerBase player = (PlayerBase) owner;
		if(player.team.pitch.ballInPlay){
			// If this is the nearest player to the ball and no receiver has been allocated
			// and it is not in the possession of a goalkeeper then chase it
			if(player.isClosestTeamMemberToBall() && player.team.getReceivingPlayer() == null && !player.team.pitch.ball.keeperHasBall()){
				if(player.isGoalKeeper())
					player.FSM().changeState(KeeperInterceptBall.state());
				else
					player.FSM().changeState(PlayerChaseBall.state());
				return;
			}

			if(player.team.pitch.getRegion(player.regionToUse).contains(player.pos(), 0.5)){
				player.targetPos.set(player.pos());
				if(player.isGoalKeeper())
					player.FSM().changeState(KeeperTendGoal.state());
				else
					player.FSM().changeState(PlayerWait.state());
				return;
			}
		}
		// Game is not on
		if(!player.team.pitch.ballInPlay && player.isAtTarget()){
			if(player.isGoalKeeper())
				player.FSM().changeState(KeeperTendGoal.state());
			else
				player.FSM().changeState(PlayerWait.state());
		}
	}

	@Override
	public void exit(BaseEntity owner) {
		PlayerBase player = (PlayerBase) owner;
		player.AP().arriveOff();
	}

	@Override
	public boolean onMessage(BaseEntity owner, Telegram tgram) {
		return false;
	}

}
